package cn.panda.edu.controller;


import cn.panda.edu.model.*;
import cn.panda.edu.service.*;
import cn.panda.edu.util.Constant;
import cn.panda.edu.util.MD5;
import cn.panda.edu.util.ResultDataUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itextpdf.text.*;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 类描述：控制层Student  
 * @author: 常晓菲  
 * @date： 2018-01-16 5:30:50 PM
 */
@RestController
@RequestMapping("/api/student")
@Api(description="学生端相关操作----常晓菲")
public class StudentController {

	/**
	 * 自动装载学生接口的bean
	 */
	@Autowired
	StudentService studentService;

	@Autowired
	ScoreService scoreService;

	@Autowired
	EducationService educationService;

	@Autowired
	ExamService examService;

	@Autowired
	SelectService selectService;

	@Autowired
	JudgeService judgeService;

	@Autowired
	SectionTestService sectionTestService;

	@Autowired
	TeacherService teacherService;

	@Autowired
	TeacherEvaluateService teacherEvaluateService;

	@Autowired
	ClassEvaluateService classEvaluateService ;

	
	@RequestMapping("/studentSelfInfo")
	public Map<String, Object> getStudentInfo(HttpSession session) {
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER) ;
		return ResultDataUtil.resData(200, "", studentService.selectByPrimaryKey(student.getStudentId())) ;
	}
	
	@RequestMapping("/checkStuPass")
	public Map<String, Object> checkPass(String checkPass, HttpSession session) {
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER) ;
		String password = student.getStudentPassword() ;
		String realCheckPass = MD5.encryptPassword(checkPass, student.getStudentName()) ;
		if (password.equals(realCheckPass)) {
			return ResultDataUtil.resData(200, "", null) ;
		} else {
			return ResultDataUtil.resData(500, "", null) ;
		}
	}
	/**
	 * 
	* @Title: getStudentById 
	* @Description: 根据id获取学生预约成功的考试信息,显示准考证上的信息
	* @return  
	* Student
	 */
	@ApiOperation(value="获取学生信息" , notes="")//用以指明api名称 
	@RequestMapping(value="/getStudentInfo", method=RequestMethod.POST)
	public Map<String, Object> getStudentById(HttpSession session){
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER);
		int orderState = 1;   //预约状态（已预约）
		return ResultDataUtil.resData(200, "", studentService.selectWithExamByPrimaryKey(student.getStudentId(),orderState));
	}
	
	@RequestMapping("/updateStudentInfo")
	public Map<String, Object> updateStudentInfo(HttpSession session , @RequestParam(required=false)String newEmail, @RequestParam(required=false)String newPhone) {
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER) ;
		if (newEmail != null && ! "".equals(newEmail)) {
			student.setStudentEmail(newEmail);
		}
		if (newPhone != null && ! "".equals(newPhone)) {
			student.setStudentPhone(newPhone);
		}
		int i = studentService.updateByPrimaryKeySelective(student) ;
		if (i > 0) {
			return ResultDataUtil.resData(200, "更新成功", null) ;
		} else {
			return ResultDataUtil.resData(500, "更新失败", null);
		}
	}
	/**
	 * 
	* @Title: listScoreByStuId 
	* @Description: 根据学生id分页获取成绩
	* @param stuId
	* @return  
	* PageInfo<Score>
	 */
	@ApiOperation(value="获取学生成绩", notes="根据学生id获取该学生所有成绩")
	@ApiImplicitParam(name="pageIndex",value="当前页码",required=true,dataType="int",paramType="form")
	@RequestMapping(value="/listScore", method=RequestMethod.POST)
	public Object listScoreByStuId(HttpSession session,Integer pageIndex){
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER);
		return ResultDataUtil.resData(200, "", scoreService.listScoreByPage(student.getStudentId(), pageIndex, Constant.PAGE_SIZE));
	}
	
	@RequestMapping("/saveCourseEvaluate")
	public Map<String, Object> classEvaluate(ClassEvaluate classEvaluate, HttpSession session) {
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER) ;
		classEvaluate.setStudentId(student.getStudentId());
		classEvaluate.setClassEvaluateDate(new Date());
		int i = classEvaluateService.addClassEvaluate(classEvaluate) ;
		if (i > 0) {
			return ResultDataUtil.resData(200, "评价成功", null);
		} else {
			return ResultDataUtil.resData(500, "评价未能成功", null);
		}
		
	}
	/**
	 * 
	* @Title: listEduByMajorId 
	* @Description: 根据专业id获取该专业的教学计划
	* @param student
	* @param pageIndex
	* @return  
	* PageInfo<Education>
	 */
	@ApiOperation(value="获取某专业的教学计划")
	@ApiImplicitParam(name="pageIndex",value="当前页码",required=true,dataType="int",defaultValue="1",paramType="form")
	@RequestMapping(value="/listEducation",method=RequestMethod.POST)
	public Object listEduByMajorId(HttpSession session,@RequestParam(value="pageIndex",defaultValue="1") Integer pageIndex){
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER);
		return ResultDataUtil.resData(200, "", educationService.listEduByMajorIdAndPage(student.getMajorId(),pageIndex,Constant.PAGE_SIZE));
	}
	
	/**
	 * 
	* @Title: listExamOrder 
	* @Description: 根据学生id获取考试信息
	* @param session
	* @return  
	* PageInfo<Exam>
	 */
	@ApiOperation(value="获取该学生的考试安排")
	@ApiImplicitParam(name="pageIndex",value="当前页码",required=true,dataType="int",defaultValue="1",paramType="form")
	@RequestMapping(value="/listExamOrder",method=RequestMethod.POST)
	public Object listExamOrder(HttpSession session ,Integer pageIndex){
		PageHelper.startPage(pageIndex, Constant.PAGE_SIZE);
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER);
		List<Exam> list = studentService.selectWithExamByPrimaryKey(student.getStudentId(), null).getExams();
		PageInfo<Exam> pageInfo = new PageInfo<>(list);
		return ResultDataUtil.resData(200, "", pageInfo);
	}
	
	/**
	 * 
	* @Title: examOrder 
	* @Description: 预约考试 
	* @param session
	* @param examId
	* @return  
	* Map<String,Object>
	 */
	@ApiOperation(value="预约考试")
	@ApiImplicitParam(name="examId",value="考试信息id",paramType="form",required=true,dataType="int")
	@RequestMapping(value="/saveExamOrder",method=RequestMethod.POST)
	public Map<String, Object> examOrder(HttpSession session ,Integer examId){
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER);
		Date appointTime = examService.getExamById(examId).getExamAppointTime();
		Date date = new Date();
		if(date.after(appointTime) || date.toString().equals(appointTime.toString())){
			ExamOrder examOrder = new ExamOrder();
			examOrder.setExamId(examId);
			examOrder.setStuId(student.getStudentId());
			examOrder.setOrderState(1);
			examService.saveExamOrder(examOrder);
			
			return ResultDataUtil.resData(200, "预约成功", null);
		}
		
		return ResultDataUtil.resData(500, "不在考试预约时间内，请过段时间再来！", null);
	}
	
	
	/**
	 * 
	* @Title: listExamPaper 
	* @Description: 根据课程id获取对应的试卷
	* @param courseId
	* @return  
	* Map<String,Object>
	 */
	@ApiOperation(value="根据课程id获取对应的试卷")
	@ApiImplicitParam(name = "courseId" , value = "课程id", dataType="int", paramType="form", required=true)
	@RequestMapping(value="/listExamPaper",method=RequestMethod.POST)
	public Map<String, Object> listExamPaper(Integer courseId){
		Map<String,Object> map = new HashMap<>();
		List<Select> selects = selectService.listSelectByCourseId(courseId, 1, 5).getList();
		List<Judge> judges = judgeService.listJudgeByCourseId(courseId, 1, 5).getList();
		map.put("selects", selects);
		map.put("judges", judges);
		return ResultDataUtil.resData(200, "", map);
	}
	
	
	/**
	 * 
	* @Title: examScore 
	* @Description: TODO(添加考试成绩) 
	* @param session
	* @param examScore
	* @param courseId
	* @return  
	* Map<String,Object>
	 */
	@RequestMapping(value="/saveScore",method=RequestMethod.POST)
	@ApiOperation("添加考试成绩")
	@ApiImplicitParams({
		@ApiImplicitParam(name="examScore",value="考试分数",dataType="int",paramType="form",required=true),
		@ApiImplicitParam(name="courseId",value="课程id",dataType="int",paramType="form",required=true)
	})
	public Map<String, Object> examScore(HttpSession session,Integer total, Integer courseId){
			int status=200;
			int stuId = ((Student)session.getAttribute(Constant.LOGIN_USER)).getStudentId();
			String message=null;
		try {
			Score score = new Score();
			score.setCourseId(courseId);
			score.setScoreExam(total);
			score.setScoreCreateDate(new Date());
			score.setStudentId(stuId);
			score.setScoreDelete(0);
			scoreService.saveScore(score);
			message="添加成功";
		} catch (Exception e) {
			status=500;
			message="添加失败";
			e.printStackTrace();
		}
		return ResultDataUtil.resData(status, message, null);
	}
	
	
	
	/**
	 * 
	* @Title: listSectionTest 
	* @Description: 获取章节测试列表
	* @return  
	* PageInfo<SectionTest>
	 */
	@ApiOperation(value="获取章节测试列表")
	@ApiImplicitParam(name="pageIndex",value="当前页码",required=true,dataType="int",defaultValue="1",paramType="form")
	@RequestMapping(value="/listSectionTest",method=RequestMethod.POST)
	public Object listSectionTest(Integer pageIndex){
		return ResultDataUtil.resData(200, "", sectionTestService.listSectionTestByPage(pageIndex, Constant.PAGE_SIZE));
	}
	
	/**
	 * 
	* @Title: listSectionTestPaper 
	* @Description: 根据章节测试id获取对应的测试题目
	* @param sectionTestId
	* @return  
	* Map<String,Object>
	 */
	@ApiOperation(value="根据章节测试id获取对应的测试题目")
	@ApiImplicitParam(name="sectionTestId", value="章节测试id", required=true, dataType="int", paramType="form")
	@RequestMapping(value="/listSectionTestPaper", method=RequestMethod.POST)
	public Map<String, Object> listSectionTestPaper(Integer sectionTestId){
		Map<String, Object> map = new HashMap<>();
		List<Judge> judges  = judgeService.listJudgeBySectionTestId(sectionTestId, 1, 5).getList();
		List<Select> selects = selectService.listSelectBySectionTestId(sectionTestId, 1, 5).getList();
		map.put("judges", judges);
		map.put("selects", selects);
		return ResultDataUtil.resData(200, "", map);
	}
	
	
	/**
	 * 
	* @Title: sectionTestScore 
	* @Description: TODO(添加章节测试信息) 
	* @param sectionId
	* @param sectionScore
	* @return  
	* Map<String,Object>
	 */
	@ApiOperation(value="添加章节测试信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name="sectionId",value="章节id",required=true,dataType="int",paramType="form"),
		@ApiImplicitParam(name="sectionScore",value="章节测试分数",required=true,dataType="int",paramType="form")
	})
	@RequestMapping(value="/saveSectionTest",method=RequestMethod.POST)
	public Map<String, Object> sectionTestScore(Integer sectionId, Integer sectionScore, HttpSession session){
		int status=200;
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER) ;
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("sectionId", sectionId);
			map.put("scoreTest", sectionScore) ;
			map.put("studentId", student.getStudentId());
			sectionTestService.saveSectionTest(map);
			status=200;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			status=500;
			e.printStackTrace();
		}
		return ResultDataUtil.resData(status, "", null);
	}
	
	/**
	 * 
	* @Title: listTeacherInfo 
	* @Description: 根据学生id获取该学生所选课程的教师信息 
	* @param session
	* @return  
	* PageInfo<Teacher>
	 */
	@ApiOperation(value="获取某学生所选课程的教师信息")
	@ApiImplicitParam(name="pageIndex",value="当前页码",required=true,dataType="int",defaultValue="1",paramType="form")
	@RequestMapping(value="/listTeacherByStuId",method=RequestMethod.POST)
	public Object listTeacherInfo(HttpSession session, Integer pageIndex){
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER);
		return ResultDataUtil.resData(200, "", teacherService.listTeacherByStuIdAndPage(student.getStudentId(),pageIndex,Constant.PAGE_SIZE));
	}
	
	/**
	 * 
	* @Title: saveTeacherEvaluate 
	* @Description: TODO(教师评价) 
	* @param teacherEvaluate
	* @return  
	* Map<String,Object>
	 */
	@ApiOperation(value="教师评价")
	@ApiImplicitParam(name="teacherEvaluate",value="教师评价实体类",required=true,dataType="TeacherEvaluate")
	@RequestMapping(value="/saveTeacherEvaluate",method=RequestMethod.POST)
	public Map<String, Object> saveTeacherEvaluate(TeacherEvaluate teacherEvaluate, HttpSession session){
		Student student = (Student) session.getAttribute(Constant.LOGIN_USER);
		teacherEvaluate.setStudentId(student.getStudentId());
		teacherEvaluate.setTeacherEvaluateDate(new Date());
		teacherEvaluate.setTeacherEvaluateDelete(0);
		teacherEvaluateService.saveTeacherEvaluate(teacherEvaluate);
		return ResultDataUtil.resData(200, "", null);
	}
	
	/**
	 * 
	* @Title: outputExam 
	* @Description: TODO(使用itext输出PDF，需五步)   
	* void
	 */
	@ApiOperation(value="准考证下载")
	@RequestMapping(value="/download",method=RequestMethod.POST)
	public void outputExam(HttpServletRequest request, HttpServletResponse response){
		//告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/pdf");
		//下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=stu.pdf");
		//1.建立com.lowagie.text.Document对象的实例
		Document document = new Document();
		//2.建立一个书写器（Writer）与document对象关联，通过书写器可以将文档写入磁盘中
		try {
//			PdfWriter.getInstance(document, new FileOutputStream("E:"+File.pathSeparator+"itext"));
			PdfWriter.getInstance(document, response.getOutputStream());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Rectangle rect = new Rectangle(PageSize.B5.rotate());

		//页面背景色

		rect.setBackgroundColor(BaseColor.ORANGE);
		//3.打开文档
		document.open();
		//4.向文档中添加内容，所有向文档添加的内容都是以对象为单位
		BaseFont bfChinese = null;
		try {
//			bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}   
//		Font fontChinese = new Font(bfChinese, 12, Font.NORMAL); 
		Font font = new Font(FontFamily.SYMBOL, 30, 82);
		Chunk chunk0 = new Chunk("hello world", font);
		Chunk chunk1 = new Chunk("准考证");
		Chunk chunk2 = new Chunk("i will be fine");
		Phrase phrase = new Phrase();
		phrase.add(chunk1);
		phrase.add(chunk2);
	    Paragraph paragraph1 = new Paragraph("ceshizhi");    
	    Paragraph paragraph2 = new Paragraph (chunk2);    
	    paragraph2.setAlignment(1); //居中对齐
	    Paragraph paragraph3 = new Paragraph (phrase);    
		try {
			document.add(chunk0);
			document.add(paragraph1);
			document.add(paragraph2);
			document.add(paragraph3);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//5.关闭文档
		document.close();
	}
	
	
}
